package com.ljb.httplibrary;

import android.app.Application;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.InputStream;

/**
 * Created by ljb on 2017/6/26.
 */

public class OssUtils {
    private static final String TAG = "OssUtils";
    private static OSS oss;
    //Oss配置参数
    private static String endpoint_ = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId_ = "LTAIeulhTcVibhf0";
    private static String accessKeySecret_ = "CoLhdTp6RLJqbI4WINE36OoaC1whsz";

    //bucket名称
    public static String BUCKET_APP = "jk-cloud-app";
    public static String BUCKET_MONITOR_XML = "jk-cloud-monitor-xml";

    private static OssUtils ossUtils;

    private OssUtils() {
    }

    /**
     * 获取单例工具类
     *
     * @return 单例对象
     */
    public static OssUtils getInstance() {
        if (ossUtils == null) {
            synchronized (OssUtils.class) {
                if (ossUtils == null) {
                    ossUtils = new OssUtils();
                }
            }
        }
        return ossUtils;
    }

    /**
     * 初始化OSS
     *
     * @param accessKeyId     accessKeyId
     * @param accessKeySecret accessKeySecret
     * @param endpoint        endpoint
     */
    public void init(Application app, String accessKeyId, String accessKeySecret, String endpoint) {
        if (accessKeyId == null || accessKeySecret == null || endpoint == null || accessKeyId.isEmpty() || accessKeySecret.isEmpty() || endpoint.isEmpty()) {
            Log.d(TAG, "init: OSS初始化异常,相关参数为空");
            return;
        }

        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        oss = new OSSClient(app.getApplicationContext(), endpoint, credentialProvider);
    }


    /**
     * 本地文件上传到OSS(异步接口,直接在UI线程调用)
     *
     * @param bucketName     bucket名称
     * @param objectKey      文件名称,如果想在OSS中显示层级结构,可以把objectKey写为"folder/subfolder/file"的格式,注意不能以'/'开头
     * @param uploadFilePath 文件上传路径
     * @param ul             回调监听
     * @return task异步任务, 可以调用task.cancel()取消任务, task.waitUntilFinished()等待直到任务完成
     */

    public OSSAsyncTask uploadObject(String bucketName, String objectKey, String uploadFilePath, final UploadListener ul) {
        if (oss == null) return null;

        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, uploadFilePath);
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                if (ul != null) ul.onProgress(request, currentSize, totalSize);
            }
        });
        OSSAsyncTask task;
        task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                if (ul != null) ul.onSuccess(request, result);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                if (ul != null) ul.onFailure(request, clientExcepion, serviceException);
            }
        });
        return task;
    }

    /**
     * Oss下载文件到本地(异步接口,直接在UI线程调用)
     *
     * @param bucketName bucket名称
     * @param objectKey  文件名称
     * @param dl         回调监听
     * @return task异步任务, 可以调用task.cancel()取消任务, task.waitUntilFinished()等待直到任务完成
     */
    public OSSAsyncTask downloadObject(String bucketName, String objectKey, final DownloadListener dl) {
        if (oss == null) return null;

        GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
        OSSAsyncTask task;
        task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // 请求成功
                if (dl != null) dl.onSuccess(result.getObjectContent());
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                if (dl != null) dl.onFailure(request, clientExcepion, serviceException);
            }
        });
        return task;
    }

    /**
     * 取消指定的task
     *
     * @param task 异步任务
     */
    public void cancel(OSSAsyncTask task) {
        if (task != null && !task.isCanceled()) {
            task.cancel();
        }
    }

    /**
     * 上传文件的回调
     */
    public interface UploadListener {
        void onProgress(PutObjectRequest request, long currentSize, long totalSize);

        void onSuccess(PutObjectRequest request, PutObjectResult result);

        void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException);
    }

    /**
     * 文件下载的回调
     */
    public interface DownloadListener {
        void onSuccess(InputStream inputStream);

        void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException);
    }
}
